#include <iostream>
#include <memory>
#include <functional>
#include <exception>
#include "Epoller.hpp"
#include <sys/types.h>
#include <sys/socket.h>

static void THandleRecv(int fd)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = '\0';
            printf("%s\n", buffer);
        }
        else
        {
            if (errno == EWOULDBLOCK || errno == EAGAIN)
            {
                printf("非阻塞\n");
                // 非阻塞，说明读完了
                break;
            }
            else if (errno == EINTR)
            {
                // 被信号干扰
                continue;
            }
            else
            {
                // 出错
                LOG(ERROR, "recv error\n");
                close(fd);
                break;
            }
        }
    }
}

void test()
{
    Epoller epl;

    epl.AddEvent(0, EPOLLIN | EPOLLET);

    while (true)
    {
        epoll_event revents[32];
        int n = epl.Wait(revents, 32, -1);
        for (int i = 0; i < n; ++i)
        {
            int fd = revents[i].data.fd;
            THandleRecv(fd);
        }
    }
}

int main(int argc, char *argv[])
{

    test();
    return 0;
}